<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>豪王益购 - 商品列表</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#FF7A00',
                        secondary: '#FFB800',
                        accent: '#FF5A00',
                        neutral: '#F8F8F8',
                        'neutral-dark': '#333333',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <!-- 自定义样式 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .card-hover {
                transition: all 0.3s ease;
            }
            .card-hover:hover {
                transform: translateY(-5px);
                box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            }
            @keyframes ping {
                75%, 100% {
                    transform: scale(1.5);
                    opacity: 0;
                }
            }
            .animate-ping {
                animation: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite;
            }
            /* 券后价标签样式 */
            .coupon-tag {
                display: inline-block;
                background: linear-gradient(90deg, #ff9000, #ff5000);
                color: white;
                padding: 0 4px;
                border-radius: 2px;
                font-size: 10px;
                line-height: 16px;
                transform: scale(0.9);
                transform-origin: left center;
                margin-left: 2px;
                vertical-align: text-bottom;
            }
            /* 防止模态框打开时页面滚动 */
            body.modal-open {
                overflow: hidden;
            }
            /* 对比模态框动画 */
            .compare-panel {
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, 100%) scale(0.9);
                transition: transform 0.3s ease-in-out, opacity 0.3s ease-in-out;
                opacity: 0;
                max-height: 90vh;
                max-width: 90vw;
                overflow: auto;
                z-index: 100;
            }
            .compare-panel.active {
                transform: translate(-50%, -50%) scale(1);
                opacity: 1;
            }
            /* 优化对比表格样式 */
            .compare-table th, .compare-table td {
                min-width: 180px;
                max-width: 250px;
                word-break: break-word;
            }
            /* 分类滚动条样式 */
            .category-scrollbar::-webkit-scrollbar {
                height: 6px;
            }
            .category-scrollbar::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 10px;
            }
            .category-scrollbar::-webkit-scrollbar-thumb {
                background: #c1c1c1;
                border-radius: 10px;
            }
            .category-scrollbar::-webkit-scrollbar-thumb:hover {
                background: #a8a8a8;
            }
            /* 全部商品标题效果 */
            .main-title {
                background: linear-gradient(90deg, #FF7A00, #FFB800);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
                position: relative;
                display: inline-block;
            }
            .main-title::after {
                content: '';
                position: absolute;
                bottom: -5px;
                left: 0;
                width: 100%;
                height: 3px;
                background: linear-gradient(90deg, #FF7A00, #FFB800);
                border-radius: 2px;
            }
            /* 收藏动画 */
            @keyframes flyToFavorite {
                0% {
                    transform: translate(0, 0) scale(1);
                    opacity: 1;
                }
                50% {
                    opacity: 0.8;
                }
                100% {
                    transform: translate(var(--end-x), var(--end-y)) scale(0.1);
                    opacity: 0;
                }
            }
            @keyframes flyFromFavorite {
                0% {
                    transform: translate(var(--start-x), var(--start-y)) scale(0.1);
                    opacity: 0;
                }
                50% {
                    opacity: 0.8;
                }
                100% {
                    transform: translate(0, 0) scale(1);
                    opacity: 1;
                }
            }
            .fly-animation {
                animation: flyToFavorite 0.8s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;
            }
            .reverse-fly-animation {
                animation: flyFromFavorite 0.8s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-50 transition-all duration-300" id="header">
        <div class="container mx-auto px-4">
            <div class="flex items-center justify-between h-16">
                <!-- 左侧Logo -->
                <div class="flex items-center">
                    <a href="#" class="flex items-center">
                        <span class="text-primary text-2xl font-bold">豪王益购</span>
                    </a>
                </div>
                <a href="index.html" class="px-4 py-2 bg-gradient-to-r from-primary to-secondary text-white rounded-full hover:opacity-90 transition-all duration-300 shadow-lg relative overflow-hidden group mr-4">
                    <span class="relative z-10">首页</span>
                    <span class="absolute inset-0 bg-gradient-to-r from-secondary to-primary opacity-0 group-hover:opacity-100 transition-opacity duration-300"></span>
                    <span class="absolute top-0 left-0 w-full h-0.5 bg-white animate-pulse"></span>
                </a>
                <!-- 中间搜索框 - 仅在中等屏幕以上显示 -->
                <div class="hidden md:flex items-center flex-1 max-w-xl mx-8">
                    <div class="relative w-full">
                        <input type="text" placeholder="搜索商品..." class="w-full py-2 pl-10 pr-4 rounded-full border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                        <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                            <i class="fa fa-search"></i>
                        </span>
                    </div>
                </div>
                
                <!-- 右侧用户、收藏和优惠券 -->
                <div class="flex items-center space-x-4">
                    <button class="p-2 rounded-full hover:bg-gray-100 transition-colors relative" id="favoriteBtn">
                        <i class="fa fa-heart text-lg text-neutral-dark"></i>
                        <span class="absolute -top-1 -right-1 bg-primary text-white text-xs w-5 h-5 flex items-center justify-center rounded-full" id="favoriteCount">0</span>
                    </button>
                    <button class="p-2 rounded-full hover:bg-gray-100 transition-colors" id="couponBtn">
                        <i class="fa fa-ticket text-lg text-neutral-dark"></i>
                    </button>
                    <button class="md:hidden p-2 rounded-full hover:bg-gray-100 transition-colors" id="mobileMenuBtn">
                        <i class="fa fa-bars text-lg text-neutral-dark"></i>
                    </button>
                </div>
            </div>
            
            <!-- 移动端搜索框 - 仅在小屏幕显示 -->
            <div class="py-3 md:hidden">
                <div class="relative">
                    <input type="text" placeholder="搜索商品..." class="w-full py-2 pl-10 pr-4 rounded-full border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                    <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                        <i class="fa fa-search"></i>
                    </span>
                </div>
            </div>
        </div>
    </header>

    <!-- 移动端分类菜单 - 默认隐藏 -->
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden transition-opacity duration-300" id="mobileMenuOverlay">
        <div class="bg-white h-full w-4/5 max-w-sm transform -translate-x-full transition-transform duration-300 ease-in-out" id="mobileMenu">
            <div class="p-4 border-b flex justify-between items-center">
                <h3 class="font-bold text-lg">商品分类</h3>
                <button id="closeMobileMenu">
                    <i class="fa fa-times text-lg"></i>
                </button>
            </div>
            <div class="p-4 space-y-2 overflow-y-auto h-[calc(100%-56px)]">
                <!-- 移动分类菜单内容将通过JS生成 -->
            </div>
        </div>
    </div>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 pt-24 pb-16">
        <!-- 页面标题 -->
        <div class="mb-6 flex items-center">
            <div>
                <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold main-title">全部商品</h1>
            </div>
            <div class="ml-8 md:block hidden">
                <!-- 大横图 -->
                <img src="商品列表图片/列表大图.jpeg" alt="大图" class="w-full h-auto rounded-lg">
            </div>
        </div>
        
        <!-- 分类导航 -->
        <div class="mb-8">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-lg font-semibold text-neutral-dark">商品分类</h2>
                <button class="text-primary flex items-center md:hidden" id="showMobileCategories">
                    <span>查看全部分类</span>
                    <i class="fa fa-chevron-right ml-1 text-xs"></i>
                </button>
            </div>
            
            <!-- 桌面端分类导航 - 添加滚动条 -->
            <div class="overflow-x-auto category-scrollbar">
                <div class="flex space-x-2 pb-2 min-w-max" id="desktopCategories">
                    <!-- 桌面分类将通过JS生成 -->
                </div>
            </div>
        </div>

        <!-- 新增排序和对比功能 -->
        <div class="mb-4 flex flex-wrap items-center gap-4">
            <!-- 新增"全部商品"按钮 -->
            <button id="resetBtn" class="px-4 py-2 bg-gradient-to-r from-primary to-secondary text-white rounded-full hover:opacity-90 transition-all duration-300 shadow-lg relative overflow-hidden group">
                <span class="relative z-10">全部商品</span>
                <span class="absolute inset-0 bg-gradient-to-r from-secondary to-primary opacity-0 group-hover:opacity-100 transition-opacity duration-300"></span>
                <span class="absolute top-0 left-0 w-full h-0.5 bg-white animate-pulse"></span>
            </button>
            <button id="compareBtn" class="px-4 py-2 bg-white border border-primary text-primary rounded-full hover:bg-primary hover:text-white transition-colors duration-300 relative">
                商品对比
                <span class="absolute -top-1 -right-1 bg-primary text-white text-xs w-5 h-5 flex items-center justify-center rounded-full" id="compareCount">0</span>
            </button>
            <button id="sortAscBtn" class="px-4 py-2 bg-white border border-primary text-primary rounded-full hover:bg-primary hover:text-white transition-colors duration-300">
                价格升序
            </button>
            <button id="sortDescBtn" class="px-4 py-2 bg-white border border-primary text-primary rounded-full hover:bg-primary hover:text-white transition-colors duration-300">
                价格降序
            </button>
        </div>
        
        <!-- 商品列表 -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6" id="productsGrid">
            <!-- 商品卡片将通过JS生成 -->
        </div>
        
        <!-- 加载更多 -->
        <div class="flex justify-center mt-12">
            <button id="loadMoreBtn" class="px-6 py-3 bg-white border border-primary text-primary rounded-full hover:bg-primary hover:text-white transition-colors duration-300 flex items-center">
                <span>加载更多</span>
                <i class="fa fa-refresh ml-2"></i>
            </button>
        </div>
    </main>

    <!-- 收藏侧边栏 -->
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden transition-opacity duration-300" id="favoriteSidebar">
        <div class="bg-white h-full w-full max-w-md ml-auto transform translate-x-full transition-transform duration-300 ease-in-out flex flex-col" id="favoritePanel">
            <div class="p-4 border-b flex justify-between items-center">
                <h3 class="font-bold text-lg">收藏商品</h3>
                <button id="closeFavoriteBtn">
                    <i class="fa fa-times text-lg"></i>
                </button>
            </div>
            
            <!-- 收藏内容 -->
            <div class="flex-1 overflow-y-auto p-4" id="favoriteItems">
                <!-- 收藏为空状态 -->
                <div class="flex flex-col items-center justify-center h-full text-gray-400" id="emptyFavorite">
                    <i class="fa fa-heart text-5xl mb-4"></i>
                    <p class="text-lg">收藏列表是空的</p>
                    <p class="text-sm mt-2">添加一些商品到收藏列表吧</p>
                </div>
                
                <!-- 收藏有商品时显示，初始隐藏 -->
                <div class="hidden space-y-4" id="favoriteItemsList">
                    <!-- 收藏商品将通过JS生成 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 商品对比模态框 -->
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden transition-opacity duration-300" id="compareModal">
        <div class="bg-white h-[90vh] w-full max-w-6xl mx-auto p-6 rounded-lg flex flex-col compare-panel" id="comparePanel">
            <div class="p-4 border-b flex justify-between items-center">
                <h3 class="font-bold text-lg">商品对比</h3>
                <button id="closeCompareBtn">
                    <i class="fa fa-times text-lg"></i>
                </button>
            </div>
            <div class="flex-1 overflow-auto" id="compareItems">
                <!-- 对比商品将通过JS生成 -->
            </div>
        </div>
    </div>

    <!-- 优惠券模态框 -->
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden transition-opacity duration-300" id="couponModal">
        <div class="bg-white h-[90vh] w-full max-w-3xl mx-auto my-10 p-6 rounded-lg transform -translate-y-full transition-transform duration-300 ease-in-out flex flex-col" id="couponPanel">
            <div class="p-4 border-b flex justify-between items-center">
                <h3 class="font-bold text-lg">优惠券列表</h3>
                <button id="closeCouponBtn">
                    <i class="fa fa-times text-lg"></i>
                </button>
            </div>
            <div class="flex-1 overflow-y-auto p-4" id="couponItems">
                <!-- 优惠券内容将通过JS生成 -->
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-white border-t">
        <div class="container mx-auto px-4 py-8">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <span class="text-primary text-xl font-bold">豪王益购</span>
                    <p class="text-gray-500 text-sm mt-1">轻松购物，愉悦生活</p>
                </div>
                <div class="flex space-x-4">
                    <a href="#" class="text-gray-500 hover:text-primary transition-colors">
                        <i class="fa fa-facebook"></i>
                    </a>
                    <a href="#" class="text-gray-500 hover:text-primary transition-colors">
                        <i class="fa fa-twitter"></i>
                    </a>
                    <a href="#" class="text-gray-500 hover:text-primary transition-colors">
                        <i class="fa fa-instagram"></i>
                    </a>
                    <a href="#" class="text-gray-500 hover:text-primary transition-colors">
                        <i class="fa fa-linkedin"></i>
                    </a>
                </div>
            </div>
            <div class="border-t mt-6 pt-6 text-center text-gray-500 text-sm">
                &copy; 2025 豪王益购 保留所有权利.
            </div>
        </div>
    </footer>

    <script>
        // 商品数据
        const categories = [
            { id: 0, name: "全部", icon: "fa-th-large" },
            { id: 1, name: "手机", icon: "fa-mobile" },
            { id: 2, name: "电脑", icon: "fa-laptop" },
            { id: 3, name: "家电", icon: "fa-television" },
            { id: 4, name: "相机", icon: "fa-camera" },
            { id: 5, name: "服装", icon: "fa-shopping-bag" },
            { id: 6, name: "鞋包", icon: "fa-suitcase" },
            { id: 7, name: "美妆", icon: "fa-paint-brush" },
            { id: 8, name: "母婴", icon: "fa-child" },
            { id: 9, name: "食品", icon: "fa-cutlery" }
        ];
        
        // 固定的45个商品数据
        const products = [
            // 手机类 (5)
            { id: 1, name: "Apple 旗舰 5G 智能手机 超高清屏幕", price: 899, originalPrice: 1099, categoryId: 1, rating: "4.8", sales: 1250, inStock: true, brand: "Apple",image: "商品列表图片/Apple 旗舰 5G 智能手机 超高清屏幕.png"},
            { id: 2, name: "Samsung 高性能折叠屏手机 长续航电池", price: 1299, originalPrice: 1499, categoryId: 1, rating: "4.7", sales: 980, inStock: true, brand: "Samsung",image: "商品列表图片/Samsung 高性能折叠屏手机 长续航电池.png"},
            { id: 3, name: "Xiaomi 智能游戏手机 快速充电", price: 799, originalPrice: 999, categoryId: 1, rating: "4.6", sales: 2100, inStock: true, brand: "Xiaomi",image: "商品列表图片/Xiaomi 智能游戏手机 快速充电.png"},
            { id: 4, name: "Huawei 专业拍照手机 超强处理器", price: 999, originalPrice: 1199, categoryId: 1, rating: "4.9", sales: 1750, inStock: true, brand: "Huawei",image: "商品列表图片/Huawei 专业拍照手机 超强处理器.png"},
            { id: 5, name: "Oppo 超薄旗舰手机 大内存", price: 899, originalPrice: 1099, categoryId: 1, rating: "4.5", sales: 1450, inStock: true, brand: "Oppo",image: "商品列表图片/Oppo 超薄旗舰手机 大内存.png"},
            
            // 电脑类 (5)
            { id: 6, name: "Apple 旗舰游戏笔记本 高性能处理器", price: 1999, originalPrice: 2299, categoryId: 2, rating: "4.8", sales: 850, inStock: true, brand: "Apple",image: "商品列表图片/Apple 旗舰游戏笔记本 高性能处理器.png"},
            { id: 7, name: "Dell 便携超薄笔记本 大内存", price: 1499, originalPrice: 1799, categoryId: 2, rating: "4.6", sales: 1200, inStock: true, brand: "Dell",image: "商品列表图片/Dell 便携超薄笔记本 大内存.png"},
            { id: 8, name: "Lenovo 商务台式机 独立显卡", price: 1299, originalPrice: 1599, categoryId: 2, rating: "4.5", sales: 950, inStock: true, brand: "Lenovo",image: "商品列表图片/Lenovo 商务台式机 独立显卡.png"},
            { id: 9, name: "HP 专业一体机 高速 SSD", price: 1599, originalPrice: 1899, categoryId: 2, rating: "4.7", sales: 780, inStock: true, brand: "HP",image: "商品列表图片/HP 专业一体机 高速 SSD.png"},
            { id: 10, name: "Asus 游戏工作站 长续航", price: 1799, originalPrice: 2099, categoryId: 2, rating: "4.9", sales: 650, inStock: true, brand: "Asus",image: "商品列表图片/Asus 游戏工作站 长续航.png"},
            
            // 家电类 (5)
            { id: 11, name: "Haier 智能智能冰箱 节能省电", price: 1899, originalPrice: 2199, categoryId: 3, rating: "4.6", sales: 420, inStock: true, brand: "Haier",image: "商品列表图片/Haier 智能智能冰箱 节能省电.png"},
            { id: 12, name: "Midea 变频空调 智能控制", price: 2199, originalPrice: 2499, categoryId: 3, rating: "4.7", sales: 380, inStock: true, brand: "Midea",image: "商品列表图片/Midea 变频空调 智能控制.png"},
            { id: 13, name: "Gree 大容量滚筒洗衣机 静音设计", price: 1499, originalPrice: 1799, categoryId: 3, rating: "4.8", sales: 510, inStock: true, brand: "Gree",image: "商品列表图片/Gree 大容量滚筒洗衣机 静音设计.png"},
            { id: 14, name: "Samsung 高端 4K 电视 快速制冷", price: 2999, originalPrice: 3499, categoryId: 3, rating: "4.9", sales: 290, inStock: true, brand: "Samsung",image: "商品列表图片/Samsung 高端 4K 电视 快速制冷.png"},
            { id: 15, name: "LG 智能扫地机器人 除菌功能", price: 1299, originalPrice: 1599, categoryId: 3, rating: "4.5", sales: 680, inStock: true, brand: "LG",image: "商品列表图片/LG 智能扫地机器人 除菌功能.png"},
            
            // 相机类 (5)
            { id: 16, name: "Canon 专业单反相机 高像素", price: 2899, originalPrice: 3299, categoryId: 4, rating: "4.9", sales: 320, inStock: true, brand: "Canon",image: "商品列表图片/专业单反相机 高像素.png"},
            { id: 17, name: "Nikon 高清微单相机 光学防抖", price: 2499, originalPrice: 2899, categoryId: 4, rating: "4.8", sales: 280, inStock: true, brand: "Nikon",image: "商品列表图片/高清微单相机 光学防抖.png"},
            { id: 18, name: "Sony 便携运动相机 4K 视频", price: 1899, originalPrice: 2199, categoryId: 4, rating: "4.7", sales: 410, inStock: true, brand: "Sony",image: "商品列表图片/便携运动相机 4K 视频.png"},
            { id: 19, name: "Fujifilm 高性能数码相机 快速对焦", price: 1999, originalPrice: 2299, categoryId: 4, rating: "4.6", sales: 350, inStock: true, brand: "Fujifilm",image: "商品列表图片/高性能数码相机 快速对焦.png"},
            { id: 20, name: "Panasonic 全画幅拍立得 长焦镜头", price: 899, originalPrice: 1099, categoryId: 4, rating: "4.5", sales: 520, inStock: true, brand: "Panasonic",image: "商品列表图片/全画幅拍立得 长焦镜头.png"},
            
            // 服装类 (5)
            { id: 21, name: "Uniqlo 休闲纯棉 T 恤", price: 99, originalPrice: 149, categoryId: 5, rating: "4.4", sales: 2850, inStock: true, brand: "Uniqlo",image: "商品列表图片/Uniqlo 休闲纯棉 T 恤.png"},
            { id: 22, name: "Zara 商务亚麻衬衫", price: 199, originalPrice: 299, categoryId: 5, rating: "4.5", sales: 1950, inStock: true, brand: "Zara",image: "商品列表图片/Zara 商务亚麻衬衫.png"},
            { id: 23, name: "H&M 时尚丝绸连衣裙", price: 149, originalPrice: 199, categoryId: 5, rating: "4.3", sales: 2250, inStock: true, brand: "H&M" ,image: "商品列表图片/H&M 时尚丝绸连衣裙.png"},
            { id: 24, name: "Nike 运动牛仔牛仔裤", price: 129, originalPrice: 179, categoryId: 5, rating: "4.6", sales: 2450, inStock: true, brand: "Nike" ,image: "商品列表图片/Nike 运动牛仔牛仔裤.png"},
            { id: 25, name: "Adidas 复古羊毛外套", price: 299, originalPrice: 399, categoryId: 5, rating: "4.7", sales: 1650, inStock: true, brand: "Adidas" ,image: "商品列表图片/Adidas 复古羊毛外套.png"},
            
            // 鞋包类 (5)
            { id: 26, name: "Nike 运动透气运动鞋", price: 299, originalPrice: 399, categoryId: 6, rating: "4.8", sales: 2250, inStock: true, brand: "Nike" ,image: "商品列表图片/Nike 运动透气运动鞋.png"},
            { id: 27, name: "Adidas 商务防滑皮鞋", price: 349, originalPrice: 449, categoryId: 6, rating: "4.7", sales: 1850, inStock: true, brand: "Adidas" ,image: "商品列表图片/Adidas 商务防滑皮鞋.png"},
            { id: 28, name: "Puma 时尚轻便凉鞋", price: 199, originalPrice: 299, categoryId: 6, rating: "4.5", sales: 2150, inStock: true, brand: "Puma",image: "商品列表图片/Puma 时尚轻便凉鞋.png" },
            { id: 29, name: "Gucci 大容量背包", price: 999, originalPrice: 1299, categoryId: 6, rating: "4.9", sales: 850, inStock: true, brand: "Gucci",image: "商品列表图片/Gucci 大容量背包.png" },
            { id: 30, name: "LV 防水手提包", price: 1299, originalPrice: 1599, categoryId: 6, rating: "4.9", sales: 720, inStock: true, brand: "LV",image: "商品列表图片/LV 防水手提包.png" },
            
            // 美妆类 (5)
            { id: 31, name: "L'Oreal 自然保湿口红", price: 89, originalPrice: 129, categoryId: 7, rating: "4.5", sales: 3250, inStock: true, brand: "L'Oreal",image: "商品列表图片/L'Oreal 自然保湿口红.png"},
            { id: 32, name: "Maybelline 哑光控油粉底液", price: 129, originalPrice: 179, categoryId: 7, rating: "4.6", sales: 2850, inStock: true, brand: "Maybelline",image: "商品列表图片/Maybelline 哑光控油粉底液.png" },
            { id: 33, name: "MAC 珠光抗衰老眼影盘", price: 199, originalPrice: 299, categoryId: 7, rating: "4.8", sales: 2150, inStock: true, brand: "MAC",image: "商品列表图片/MAC 珠光抗衰老眼影盘.png" },
            { id: 34, name: "Estee Lauder 雾面美白面膜", price: 299, originalPrice: 399, categoryId: 7, rating: "4.7", sales: 1850, inStock: true, brand: "Estee Lauder",image: "商品列表图片/Estee Lauder 雾面美白面膜.png" },
            { id: 35, name: "Dior 水光持久香水", price: 499, originalPrice: 699, categoryId: 7, rating: "4.9", sales: 1550, inStock: true, brand: "Dior",image: "商品列表图片/Dior 水光持久香水.png"},
            
            // 母婴类 (5)
            { id: 36, name: "Pigeon 有机安全奶粉", price: 199, originalPrice: 299, categoryId: 8, rating: "4.8", sales: 1850, inStock: true, brand: "Pigeon",image: "商品列表图片/Pigeon 有机安全奶粉.png" },
            { id: 37, name: "Huggies 纯棉健康纸尿裤", price: 129, originalPrice: 199, categoryId: 8, rating: "4.7", sales: 2250, inStock: true, brand: "Huggies",image: "商品列表图片/Huggies 纯棉健康纸尿裤.png" },
            { id: 38, name: "Gerber 硅胶舒适婴儿车", price: 599, originalPrice: 799, categoryId: 8, rating: "4.9", sales: 950, inStock: true, brand: "Gerber",image: "商品列表图片/Gerber 硅胶舒适婴儿车.png" },
            { id: 39, name: "Fisher-Price 塑料易清洗奶瓶", price: 79, originalPrice: 129, categoryId: 8, rating: "4.6", sales: 2850, inStock: true, brand: "Fisher-Price",image: "商品列表图片/Fisher-Price 塑料易清洗奶瓶.png" },
            { id: 40, name: "Johnson's 木质多功能玩具", price: 149, originalPrice: 199, categoryId: 8, rating: "4.5", sales: 1950, inStock: true, brand: "Johnson's",image: "商品列表图片/Johnson's 木质多功能玩具.png" },
            
            // 食品类 (5)
            { id: 41, name: "Lay's 原味健康零食", price: 19, originalPrice: 29, categoryId: 9, rating: "4.4", sales: 9850, inStock: true, brand: "Lay's",image: "商品列表图片/Lay's 原味健康零食.png" },
            { id: 42, name: "Coca-Cola 香辣低脂饮料", price: 9, originalPrice: 15, categoryId: 9, rating: "4.3", sales: 11250, inStock: true, brand: "Coca-Cola",image: "商品列表图片/Coca-Cola 香辣低脂饮料.png" },
            { id: 43, name: "Nestle 甜味无添加方便面", price: 15, originalPrice: 25, categoryId: 9, rating: "4.5", sales: 8750, inStock: true, brand: "Nestle",image: "商品列表图片/Nestle 甜味无添加方便面.png" },
            { id: 44, name: "Oreo 咸味有机巧克力", price: 29, originalPrice: 49, categoryId: 9, rating: "4.7", sales: 6850, inStock: true, brand: "Oreo",image: "商品列表图片/Oreo 咸味有机巧克力.png" },
            { id: 45, name: "Hershey's 酸味高蛋白坚果", price: 49, originalPrice: 69, categoryId: 9, rating: "4.6", sales: 4950, inStock: true, brand: "Hershey's",image: "商品列表图片/Hershey's 酸味高蛋白坚果.png" }
        ];
        
        // 设置商品图片（使用固定商品名称作为种子）
        products.forEach(product => {
    if (!product.image) {
        product.image = `https://picsum.photos/seed/${product.name}/400/400`;
    }
});
        
        // 收藏数据 - 从本地存储加载，初始为空数组
        let favorites = JSON.parse(localStorage.getItem('favorites')) || [];
        // 对比数据 - 从本地存储加载
        let compareItems = JSON.parse(localStorage.getItem('compareItems')) || [];
        // 优惠券数据，增加20个优惠券
        const coupons = [
            { id: 1, amount: 10, threshold: 100, expireDate: '2025-12-31' },
            { id: 2, amount: 20, threshold: 200, expireDate: '2025-12-31' },
            { id: 3, amount: 50, threshold: 500, expireDate: '2025-12-31' }
        ];
        for (let i = 4; i <= 23; i++) {
            const amount = Math.floor(Math.random() * 50) + 10;
            const threshold = amount * 10;
            coupons.push({ id: i, amount, threshold, expireDate: '2025-12-31' });
        }
        // 用户已领取的优惠券
        let userCoupons = JSON.parse(localStorage.getItem('userCoupons')) || [];
        
        // DOM元素
        const productsGrid = document.getElementById('productsGrid');
        const desktopCategories = document.getElementById('desktopCategories');
        const mobileCategories = document.querySelector('#mobileMenu .p-4');
        const favoriteBtn = document.getElementById('favoriteBtn');
        const favoriteSidebar = document.getElementById('favoriteSidebar');
        const favoritePanel = document.getElementById('favoritePanel');
        const closeFavoriteBtn = document.getElementById('closeFavoriteBtn');
        const favoriteItems = document.getElementById('favoriteItems');
        const emptyFavorite = document.getElementById('emptyFavorite');
        const favoriteItemsList = document.getElementById('favoriteItemsList');
        const favoriteCount = document.getElementById('favoriteCount');
        const header = document.getElementById('header');
        const mobileMenuBtn = document.getElementById('mobileMenuBtn');
        const mobileMenuOverlay = document.getElementById('mobileMenuOverlay');
        const mobileMenu = document.getElementById('mobileMenu');
        const closeMobileMenu = document.getElementById('closeMobileMenu');
        const showMobileCategories = document.getElementById('showMobileCategories');
        const loadMoreBtn = document.getElementById('loadMoreBtn');
        const couponBtn = document.getElementById('couponBtn');
        const compareBtn = document.getElementById('compareBtn');
        const sortAscBtn = document.getElementById('sortAscBtn');
        const sortDescBtn = document.getElementById('sortDescBtn');
        const resetBtn = document.getElementById('resetBtn');
        const compareModal = document.getElementById('compareModal');
        const comparePanel = document.getElementById('comparePanel');
        const closeCompareBtn = document.getElementById('closeCompareBtn');
        const compareItemsEl = document.getElementById('compareItems');
        const couponModal = document.getElementById('couponModal');
        const couponPanel = document.getElementById('couponPanel');
        const closeCouponBtn = document.getElementById('closeCouponBtn');
        const couponItems = document.getElementById('couponItems');
        const compareCount = document.getElementById('compareCount');
        
        // 当前分类筛选
        let currentCategory = 0;
        // 当前页码
        let currentPage = 1;
        // 每页显示的商品数量
        const productsPerPage = 16;
        // 当前排序方式
        let sortMethod = null;
        // 用于存储商品位置
        let productPositions = {};
        
        // 初始化函数
        function init() {
            // 渲染分类
            renderCategories();
            
            // 初始加载商品
            loadProducts();
            
            // 更新收藏计数
            updateFavoriteCount();
            
            // 更新对比计数
            updateCompareCount();
            
            // 事件监听
            favoriteBtn.addEventListener('click', toggleFavorite);
            closeFavoriteBtn.addEventListener('click', toggleFavorite);
            mobileMenuBtn.addEventListener('click', toggleMobileMenu);
            closeMobileMenu.addEventListener('click', toggleMobileMenu);
            showMobileCategories.addEventListener('click', toggleMobileMenu);
            loadMoreBtn.addEventListener('click', loadMoreProducts);
            couponBtn.addEventListener('click', toggleCoupon);
            compareBtn.addEventListener('click', toggleCompare);
            sortAscBtn.addEventListener('click', () => sortProducts('asc'));
            sortDescBtn.addEventListener('click', () => sortProducts('desc'));
            resetBtn.addEventListener('click', resetProducts);
            closeCompareBtn.addEventListener('click', toggleCompare);
            closeCouponBtn.addEventListener('click', toggleCoupon);
            
            // 添加收藏侧边栏外部点击关闭功能
            favoriteSidebar.addEventListener('click', (e) => {
                if (e.target === favoriteSidebar) {
                    toggleFavorite();
                }
            });
            
            // 滚动监听
            window.addEventListener('scroll', handleScroll);
            
            // 对比模态框初始位置修正
            comparePanel.classList.add('compare-panel');
        }
        
        // 重置商品列表
        function resetProducts() {
            currentCategory = 0;
            sortMethod = null;
            currentPage = 1;
            productsGrid.innerHTML = '';
            loadProducts();
            renderCategories();
        }
        
        // 渲染分类
        function renderCategories() {
            // 桌面端分类
            desktopCategories.innerHTML = '';
            categories.forEach(category => {
                const categoryEl = document.createElement('div');
                categoryEl.className = `flex flex-row items-center px-4 py-3 rounded-lg cursor-pointer transition-all whitespace-nowrap ${currentCategory === category.id ? 'bg-primary/10 text-primary' : 'bg-white hover:bg-gray-50'}`;
                categoryEl.innerHTML = `
                    <i class="fa ${category.icon} text-xl mr-2"></i>
                    <span class="text-sm">${category.name}</span>
                `;
                categoryEl.addEventListener('click', () => {
                    currentCategory = category.id;
                    currentPage = 1;
                    productsGrid.innerHTML = '';
                    loadProducts();
                    renderCategories();
                });
                desktopCategories.appendChild(categoryEl);
            });
            
            // 移动端分类
            mobileCategories.innerHTML = '';
            categories.forEach(category => {
                const categoryEl = document.createElement('div');
                categoryEl.className = `flex items-center px-3 py-2 rounded-lg cursor-pointer transition-all ${currentCategory === category.id ? 'bg-primary/10 text-primary' : 'hover:bg-gray-50'}`;
                categoryEl.innerHTML = `
                    <i class="fa ${category.icon} mr-3"></i>
                    <span>${category.name}</span>
                `;
                categoryEl.addEventListener('click', () => {
                    currentCategory = category.id;
                    currentPage = 1;
                    productsGrid.innerHTML = '';
                    loadProducts();
                    renderCategories();
                    toggleMobileMenu();
                });
                mobileCategories.appendChild(categoryEl);
            });
        }
        
        // 加载商品
        function loadProducts() {
            // 筛选商品
            let filteredProducts = products;
            if (currentCategory !== 0) {
                filteredProducts = products.filter(product => product.categoryId === currentCategory);
            }
            
            // 排序商品
            if (sortMethod === 'asc') {
                filteredProducts.sort((a, b) => a.price - b.price);
            } else if (sortMethod === 'desc') {
                filteredProducts.sort((a, b) => b.price - a.price);
            } else {
                // 恢复原始顺序（按id排序）
                filteredProducts.sort((a, b) => a.id - b.id);
            }
            
            // 计算当前页的商品
            const startIndex = (currentPage - 1) * productsPerPage;
            const endIndex = startIndex + productsPerPage;
            const paginatedProducts = filteredProducts.slice(startIndex, endIndex);
            
            // 渲染商品
            paginatedProducts.forEach(product => {
                renderProduct(product);
            });
            
            // 检查是否还有更多商品
            if (endIndex >= filteredProducts.length) {
                loadMoreBtn.innerHTML = '<span>没有更多商品了</span>';
                loadMoreBtn.disabled = true;
                loadMoreBtn.classList.add('opacity-50', 'cursor-not-allowed');
            } else {
                loadMoreBtn.innerHTML = '<span>加载更多</span><i class="fa fa-refresh ml-2"></i>';
                loadMoreBtn.disabled = false;
                loadMoreBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            }
        }
        
        // 加载更多商品
        function loadMoreProducts() {
            currentPage++;
            loadProducts();
        }
        
        // 渲染单个商品
        function renderProduct(product) {
            const discount = Math.round(((product.originalPrice - product.price) / product.originalPrice) * 100);
            const isFavorite = favorites.some(item => item.id === product.id);
            const isInCompare = compareItems.some(item => item.id === product.id);
            const applicableCoupons = userCoupons.filter(coupon => product.price >= coupon.threshold);
            const maxCoupon = applicableCoupons.reduce((max, coupon) => coupon.amount > max.amount ? coupon : max, { amount: 0 });
            const couponPrice = product.price - maxCoupon.amount;
            const hasCoupon = maxCoupon.amount > 0;

            const productEl = document.createElement('div');
            productEl.className = 'bg-white rounded-xl overflow-hidden shadow-sm card-hover';
            productEl.setAttribute('data-id', product.id);
            productEl.innerHTML = `
                <div class="relative">
                    <img src="${product.image}" alt="${product.name}" class="w-full h-48 object-cover">
                    ${discount > 0 ? `<div class="absolute top-2 left-2 bg-primary text-white text-xs font-bold px-2 py-1 rounded">${discount}% 折扣</div>` : ''}
                    ${!product.inStock ? `<div class="absolute inset-0 bg-black bg-opacity-40 flex items-center justify-center">
                        <span class="bg-red-500 text-white text-xs font-bold px-3 py-1 rounded-full">缺货</span>
                    </div>` : ''}
                </div>
                <div class="p-4">
                    <div class="flex items-center text-yellow-400 text-xs mb-1">
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star${product.rating < 4.5 ? '-half-o' : ''}"></i>
                        <span class="text-gray-500 ml-1">${product.rating}</span>
                    </div>
                    <h3 class="font-medium text-neutral-dark mb-1 line-clamp-2 h-10">${product.name}</h3>
                    <div class="flex items-center justify-between mt-3">
                        <div>
                            ${hasCoupon ? `
                                <div class="flex items-center">
                                    <span class="text-primary font-bold text-lg">¥${couponPrice.toFixed(2)}</span>
                                    <span class="coupon-tag">券后价</span>
                                    <span class="text-gray-400 text-sm line-through ml-2">¥${product.price.toFixed(2)}</span>
                                </div>
                            ` : `<span class="text-primary font-bold text-lg">¥${product.price.toFixed(2)}</span>`}
                            ${product.originalPrice > product.price ? `<span class="text-gray-400 text-sm line-through">¥${product.originalPrice.toFixed(2)}</span>` : ''}
                        </div>
                        <div class="flex">
                            <button class="w-8 h-8 rounded-full flex items-center justify-center hover:bg-primary hover:text-white transition-colors duration-300 ${isFavorite ? 'bg-red-500 text-white' : 'bg-primary/10 text-primary'}" onclick="toggleFavoriteProduct(event, ${product.id})">
                                <i class="fa fa-heart"></i>
                            </button>
                            <button class="w-8 h-8 rounded-full bg-primary/10 text-primary flex items-center justify-center hover:bg-primary hover:text-white transition-colors duration-300 ml-2 ${isInCompare ? 'bg-primary text-white' : ''}" onclick="toggleCompareProduct(event, ${product.id})">
                                <i class="fa fa-balance-scale"></i>
                            </button>
                        </div>
                    </div>
                    <div class="text-gray-500 text-sm mt-1">销量: ${product.sales}件</div>
                </div>
            `;
            productsGrid.appendChild(productEl);
            
            // 存储商品位置
            const rect = productEl.getBoundingClientRect();
            productPositions[product.id] = {
                top: rect.top + window.scrollY,
                left: rect.left + window.scrollX,
                width: rect.width,
                height: rect.height
            };
        }
        
        // 切换商品收藏状态
        function toggleFavoriteProduct(event, productId) {
            // 防止页面跳转
            event.preventDefault();
            event.stopPropagation();
            
            // 保存当前滚动位置
            const scrollPosition = window.scrollY;
            
            const product = products.find(p => p.id === productId);
            if (!product) return;
            
            const favoriteIndex = favorites.findIndex(item => item.id === productId);
            const isAdding = favoriteIndex === -1;
            
            if (isAdding) {
                favorites.push({
                    id: product.id,
                    name: product.name,
                    price: product.price,
                    image: product.image
                });
            } else {
                favorites.splice(favoriteIndex, 1);
            }
            
            // 更新收藏状态
            updateFavoriteStatus();
            
            if (isAdding) {
                showFavorite();
            }
            
            // 添加收藏动画
            const productCard = event.target.closest('.card-hover');
            if (productCard) {
                const clone = productCard.cloneNode(true);
                clone.style.position = 'fixed';
                clone.style.top = `${productCard.getBoundingClientRect().top}px`;
                clone.style.left = `${productCard.getBoundingClientRect().left}px`;
                clone.style.width = `${productCard.offsetWidth}px`;
                clone.style.height = `${productCard.offsetHeight}px`;
                clone.style.zIndex = '1000';
                clone.style.transition = 'none';
                clone.style.opacity = '0.8';
                clone.style.pointerEvents = 'none';
                document.body.appendChild(clone);
                
                const favoriteIcon = favoriteBtn.getBoundingClientRect();
                
                if (isAdding) {
                    // 添加到收藏的动画
                    clone.style.setProperty('--end-x', `${favoriteIcon.left - clone.getBoundingClientRect().left}px`);
                    clone.style.setProperty('--end-y', `${favoriteIcon.top - clone.getBoundingClientRect().top}px`);
                    clone.classList.add('fly-animation');
                } else {
                    // 从收藏移除的动画
                    const startX = favoriteIcon.left - (productPositions[productId].left - window.scrollX);
                    const startY = favoriteIcon.top - (productPositions[productId].top - window.scrollY);
                    
                    clone.style.setProperty('--start-x', `${startX}px`);
                    clone.style.setProperty('--start-y', `${startY}px`);
                    clone.classList.add('reverse-fly-animation');
                }
                
                setTimeout(() => {
                    document.body.removeChild(clone);
                    
                    // 收藏图标动画
                    favoriteBtn.classList.add('animate-ping');
                    setTimeout(() => favoriteBtn.classList.remove('animate-ping'), 600);
                    
                    // 恢复滚动位置
                    window.scrollTo(0, scrollPosition);
                    
                    // 更新按钮状态
                    const buttons = document.querySelectorAll(`[onclick="toggleFavoriteProduct(event, ${productId})"]`);
                    buttons.forEach(button => {
                        button.className = button.className.replace('bg-primary/10', '').replace('bg-red-500', '');
                        if (isAdding) {
                            button.classList.add('bg-red-500', 'text-white');
                        } else {
                            button.classList.add('bg-primary/10', 'text-primary');
                        }
                    });
                }, 800);
            } else {
                // 没有动画时立即恢复滚动位置
                window.scrollTo(0, scrollPosition);
                
                // 更新按钮状态
                const buttons = document.querySelectorAll(`[onclick="toggleFavoriteProduct(event, ${productId})"]`);
                buttons.forEach(button => {
                    button.className = button.className.replace('bg-primary/10', '').replace('bg-red-500', '');
                    button.classList.add('bg-primary/10', 'text-primary');
                });
            }
        }
        
        // 更新收藏状态
        function updateFavoriteStatus() {
            // 保存到本地存储
            localStorage.setItem('favorites', JSON.stringify(favorites));
            
            // 更新收藏项目
            updateFavoriteItems();
            
            // 更新收藏计数
            updateFavoriteCount();
        }
        
        // 更新收藏项目
        function updateFavoriteItems() {
            if (favorites.length === 0) {
                emptyFavorite.classList.remove('hidden');
                favoriteItemsList.classList.add('hidden');
                return;
            }
            
            emptyFavorite.classList.add('hidden');
            favoriteItemsList.classList.remove('hidden');
            favoriteItemsList.innerHTML = '';
            
            favorites.forEach(item => {
                const favoriteItemEl = document.createElement('div');
                favoriteItemEl.className = 'flex items-center justify-between pb-4 border-b';
                favoriteItemEl.innerHTML = `
                    <div class="flex items-center">
                        <img src="${item.image}" alt="${item.name}" class="w-16 h-16 object-cover rounded-lg">
                        <div class="ml-3">
                            <h4 class="font-medium text-neutral-dark line-clamp-1">${item.name}</h4>
                            <p class="text-primary font-bold">¥${item.price.toFixed(2)}</p>
                        </div>
                    </div>
                    <button class="text-gray-400 hover:text-red-500 transition-colors" onclick="removeFromFavorites(${item.id})">
                        <i class="fa fa-trash"></i>
                    </button>
                `;
                favoriteItemsList.appendChild(favoriteItemEl);
            });
        }
        
        // 更新收藏计数
        function updateFavoriteCount() {
            const count = favorites.length;
            favoriteCount.textContent = count;
        }
        
        // 更新对比计数
        function updateCompareCount() {
            const count = compareItems.length;
            compareCount.textContent = count;
        }
        
        // 从收藏移除商品
        function removeFromFavorites(productId) {
            favorites = favorites.filter(item => item.id !== productId);
            updateFavoriteStatus();
        }
        
        // 显示/隐藏收藏
        function toggleFavorite() {
            favoriteSidebar.classList.toggle('hidden');
            setTimeout(() => {
                favoritePanel.classList.toggle('translate-x-full');
            }, 10);
        }
        
        // 显示收藏
        function showFavorite() {
            favoriteSidebar.classList.remove('hidden');
            setTimeout(() => {
                favoritePanel.classList.remove('translate-x-full');
            }, 10);
        }
        
        // 显示/隐藏移动菜单
        function toggleMobileMenu() {
            mobileMenuOverlay.classList.toggle('hidden');
            setTimeout(() => {
                mobileMenu.classList.toggle('-translate-x-full');
            }, 10);
        }
        
        // 处理滚动事件
        function handleScroll() {
            if (window.scrollY > 100) {
                header.classList.add('shadow-md', 'bg-white/95', 'backdrop-blur-sm');
            } else {
                header.classList.remove('shadow-md', 'bg-white/95', 'backdrop-blur-sm');
            }
        }

        // 排序商品
        function sortProducts(method) {
            sortMethod = method;
            currentPage = 1;
            productsGrid.innerHTML = '';
            loadProducts();
        }

        // 切换商品对比状态
        function toggleCompareProduct(event, productId) {
            event.preventDefault();
            event.stopPropagation();
            
            const product = products.find(p => p.id === productId);
            if (!product) return;

            const compareIndex = compareItems.findIndex(item => item.id === productId);
            if (compareIndex === -1) {
                // 最多允许对比4个商品
                if (compareItems.length >= 4) {
                    alert('最多只能对比4个商品');
                    return;
                }
                compareItems.push({
                    id: product.id,
                    name: product.name,
                    price: product.price,
                    originalPrice: product.originalPrice,
                    image: product.image,
                    rating: product.rating,
                    sales: product.sales,
                    inStock: product.inStock,
                    brand: product.brand
                });
            } else {
                compareItems.splice(compareIndex, 1);
            }

            // 保存对比列表到localStorage
            localStorage.setItem('compareItems', JSON.stringify(compareItems));
            
            updateCompareCount();
            
            // 更新当前页面的商品卡片状态
            const productCards = productsGrid.querySelectorAll('.card-hover');
            productCards.forEach(card => {
                const cardId = parseInt(card.getAttribute('data-id'));
                if (cardId === productId) {
                    const compareBtn = card.querySelector('button[onclick^="toggleCompareProduct"]');
                    if (compareIndex === -1) {
                        compareBtn.classList.add('bg-primary', 'text-white');
                    } else {
                        compareBtn.classList.remove('bg-primary', 'text-white');
                    }
                }
            });
        }

        // 更新对比项目
        function updateCompareItems() {
            compareItemsEl.innerHTML = '';
            if (compareItems.length === 0) {
                compareItemsEl.innerHTML = '<p class="text-gray-400 text-center p-4">请选择要对比的商品（最多4个）</p>';
                return;
            }

            const table = document.createElement('div');
            table.className = 'min-w-full overflow-x-auto';

            const tableContent = document.createElement('table');
            tableContent.className = 'w-full border-collapse compare-table';
            table.appendChild(tableContent);

            // 创建表头
            const headerRow = document.createElement('tr');
            headerRow.className = 'bg-gray-50 sticky top-0 z-10';
            
            // 空表头
            const emptyHeader = document.createElement('th');
            emptyHeader.className = 'border p-3 text-left min-w-[180px]';
            headerRow.appendChild(emptyHeader);
            
            // 商品表头
            compareItems.forEach(product => {
                const th = document.createElement('th');
                th.className = 'border p-3 text-left';
                th.innerHTML = `
                    <div class="flex flex-col items-center">
                        <img src="${product.image}" alt="${product.name}" class="w-24 h-24 object-cover mb-2">
                        <h4 class="font-medium text-sm line-clamp-2">${product.name}</h4>
                        <button class="mt-2 text-red-500 text-sm" onclick="removeFromCompare(${product.id})">
                            <i class="fa fa-trash mr-1"></i>移除
                        </button>
                    </div>
                `;
                headerRow.appendChild(th);
            });
            tableContent.appendChild(headerRow);
            
            // 价格行
            const priceRow = document.createElement('tr');
            priceRow.innerHTML = '<td class="border p-3 bg-gray-50 font-semibold">价格</td>';
            compareItems.forEach(product => {
                const td = document.createElement('td');
                td.className = 'border p-3';
                td.textContent = `¥${product.price.toFixed(2)}`;
                priceRow.appendChild(td);
            });
            tableContent.appendChild(priceRow);
            
            // 原价行
            const originalPriceRow = document.createElement('tr');
            originalPriceRow.innerHTML = '<td class="border p-3 bg-gray-50 font-semibold">原价</td>';
            compareItems.forEach(product => {
                const td = document.createElement('td');
                td.className = 'border p-3';
                td.textContent = `¥${product.originalPrice.toFixed(2)}`;
                originalPriceRow.appendChild(td);
            });
            tableContent.appendChild(originalPriceRow);
            
            // 评分行
            const ratingRow = document.createElement('tr');
            ratingRow.innerHTML = '<td class="border p-3 bg-gray-50 font-semibold">评分</td>';
            compareItems.forEach(product => {
                const td = document.createElement('td');
                td.className = 'border p-3';
                td.innerHTML = `
                    <div class="flex items-center text-yellow-400">
                        <i class="fa fa-star text-xs"></i>
                        <i class="fa fa-star text-xs"></i>
                        <i class="fa fa-star text-xs"></i>
                        <i class="fa fa-star text-xs"></i>
                        <i class="fa fa-star${product.rating < 4.5 ? '-half-o' : ''} text-xs"></i>
                        <span class="text-gray-500 ml-1 text-sm">${product.rating}</span>
                    </div>
                `;
                ratingRow.appendChild(td);
            });
            tableContent.appendChild(ratingRow);
            
            // 销量行
            const salesRow = document.createElement('tr');
            salesRow.innerHTML = '<td class="border p-3 bg-gray-50 font-semibold">销量</td>';
            compareItems.forEach(product => {
                const td = document.createElement('td');
                td.className = 'border p-3';
                td.textContent = `${product.sales}件`;
                salesRow.appendChild(td);
            });
            tableContent.appendChild(salesRow);
            
            // 品牌行
            const brandRow = document.createElement('tr');
            brandRow.innerHTML = '<td class="border p-3 bg-gray-50 font-semibold">品牌</td>';
            compareItems.forEach(product => {
                const td = document.createElement('td');
                td.className = 'border p-3';
                td.textContent = product.brand;
                brandRow.appendChild(td);
            });
            tableContent.appendChild(brandRow);
            
            // 库存行
            const stockRow = document.createElement('tr');
            stockRow.innerHTML = '<td class="border p-3 bg-gray-50 font-semibold">库存</td>';
            compareItems.forEach(product => {
                const td = document.createElement('td');
                td.className = 'border p-3';
                td.innerHTML = product.inStock ? 
                    '<span class="text-green-500">有货</span>' : 
                    '<span class="text-red-500">缺货</span>';
                stockRow.appendChild(td);
            });
            tableContent.appendChild(stockRow);
            
            compareItemsEl.appendChild(table);
        }

        // 从对比移除商品
        function removeFromCompare(productId) {
            compareItems = compareItems.filter(item => item.id !== productId);
            // 保存对比列表到localStorage
            localStorage.setItem('compareItems', JSON.stringify(compareItems));
            updateCompareItems();
            updateCompareCount();
            
            // 更新商品列表中的对比按钮状态
            const productCards = productsGrid.querySelectorAll('.card-hover');
            productCards.forEach(card => {
                const cardId = parseInt(card.getAttribute('data-id'));
                if (cardId === productId) {
                    const compareBtn = card.querySelector('button[onclick^="toggleCompareProduct"]');
                    compareBtn.classList.remove('bg-primary', 'text-white');
                }
            });
        }

        // 显示/隐藏商品对比模态框
        function toggleCompare() {
            const isOpening = compareModal.classList.toggle('hidden');
            if (!isOpening) {
                // 打开模态框
                document.body.classList.add('modal-open');
                
                // 更新对比内容
                updateCompareItems();
                
                // 添加动画类
                setTimeout(() => {
                    comparePanel.classList.add('active');
                }, 10);
            } else {
                // 关闭模态框
                document.body.classList.remove('modal-open');
                
                // 移除动画类
                comparePanel.classList.remove('active');
            }
        }

        // 显示/隐藏优惠券模态框
        function toggleCoupon() {
            couponModal.classList.toggle('hidden');
            setTimeout(() => {
                couponPanel.classList.toggle('-translate-y-full');
            }, 10);

            // 渲染优惠券列表
            renderCouponItems();
        }
        
        // 渲染优惠券列表
        function renderCouponItems() {
            couponItems.innerHTML = '';
            coupons.forEach(coupon => {
                const isClaimed = userCoupons.some(userCoupon => userCoupon.id === coupon.id);
                const couponEl = document.createElement('div');
                couponEl.className = `flex items-center justify-between p-4 border-b rounded-lg mb-3 bg-gray-50 ${isClaimed ? 'opacity-50' : ''}`;
                couponEl.innerHTML = `
                    <div>
                        <p class="text-primary font-bold text-lg">¥${coupon.amount} 优惠券</p>
                        <p class="text-gray-500">满 ${coupon.threshold} 元可用</p>
                        <p class="text-gray-500">有效期至: ${coupon.expireDate}</p>
                    </div>
                    <button class="px-4 py-2 bg-primary text-white rounded-full ${isClaimed ? 'hidden' : ''}" onclick="claimCoupon(${coupon.id})">领取</button>
                    <div class="px-4 py-2 text-gray-500 ${isClaimed ? '' : 'hidden'}">已领取</div>
                `;
                couponItems.appendChild(couponEl);
            });
        }

        // 领取优惠券
        function claimCoupon(couponId) {
            const coupon = coupons.find(c => c.id === couponId);
            if (!coupon) return;

            if (!userCoupons.some(userCoupon => userCoupon.id === couponId)) {
                userCoupons.push(coupon);
                localStorage.setItem('userCoupons', JSON.stringify(userCoupons));
                
                // 重新渲染优惠券列表（不关闭模态框）
                renderCouponItems();
                
                // 重新渲染商品列表
                productsGrid.innerHTML = '';
                loadProducts();
            }
        }

        // 初始化页面
        init();
    </script>
</body>
</html>